manifest.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  1. # -*- coding: utf-8 -*-
  2. #
  3. # Copyright (C) 2012-2013 Python Software Foundation.
  4. # See LICENSE.txt and CONTRIBUTORS.txt.
  5. #
  6. """
  7. Class representing the list of files in a distribution.
  8. Equivalent to distutils.filelist, but fixes some problems.
  9. """
  10. import fnmatch
  11. import logging
  12. import os
  13. import re
  14. import sys
  15. from . import DistlibException
  16. from .compat import fsdecode
  17. from .util import convert_path
  18. __all__ = ['Manifest']
  19. logger = logging.getLogger(__name__)
  20. # a \ followed by some spaces + EOL
  21. _COLLAPSE_PATTERN = re.compile('\\\\w*\n', re.M)
  22. _COMMENTED_LINE = re.compile('#.*?(?=\n)|\n(?=$)', re.M | re.S)
  23. #
  24. # Due to the different results returned by fnmatch.translate, we need
  25. # to do slightly different processing for Python 2.7 and 3.2 ... this needed
  26. # to be brought in for Python 3.6 onwards.
  27. #
  28. _PYTHON_VERSION = sys.version_info[:2]
  29. class Manifest(object):
  30. """A list of files built by on exploring the filesystem and filtered by
  31. applying various patterns to what we find there.
  32. """
  33. def __init__(self, base=None):
  34. """
  35. Initialise an instance.
  36. :param base: The base directory to explore under.
  37. """
  38. self.base = os.path.abspath(os.path.normpath(base or os.getcwd()))
  39. self.prefix = self.base + os.sep
  40. self.allfiles = None
  41. self.files = set()
  42. #
  43. # Public API
  44. #
  45. def findall(self):
  46. """Find all files under the base and set ``allfiles`` to the absolute
  47. pathnames of files found.
  48. """
  49. from stat import S_ISREG, S_ISDIR, S_ISLNK
  50. self.allfiles = allfiles = []
  51. root = self.base
  52. stack = [root]
  53. pop = stack.pop
  54. push = stack.append
  55. while stack:
  56. root = pop()
  57. names = os.listdir(root)
  58. for name in names:
  59. fullname = os.path.join(root, name)
  60. # Avoid excess stat calls -- just one will do, thank you!
  61. stat = os.stat(fullname)
  62. mode = stat.st_mode
  63. if S_ISREG(mode):
  64. allfiles.append(fsdecode(fullname))
  65. elif S_ISDIR(mode) and not S_ISLNK(mode):
  66. push(fullname)
  67. def add(self, item):
  68. """
  69. Add a file to the manifest.
  70. :param item: The pathname to add. This can be relative to the base.
  71. """
  72. if not item.startswith(self.prefix):
  73. item = os.path.join(self.base, item)
  74. self.files.add(os.path.normpath(item))
  75. def add_many(self, items):
  76. """
  77. Add a list of files to the manifest.
  78. :param items: The pathnames to add. These can be relative to the base.
  79. """
  80. for item in items:
  81. self.add(item)
  82. def sorted(self, wantdirs=False):
  83. """
  84. Return sorted files in directory order
  85. """
  86. def add_dir(dirs, d):
  87. dirs.add(d)
  88. logger.debug('add_dir added %s', d)
  89. if d != self.base:
  90. parent, _ = os.path.split(d)
  91. assert parent not in ('', '/')
  92. add_dir(dirs, parent)
  93. result = set(self.files) # make a copy!
  94. if wantdirs:
  95. dirs = set()
  96. for f in result:
  97. add_dir(dirs, os.path.dirname(f))
  98. result |= dirs
  99. return [os.path.join(*path_tuple) for path_tuple in
  100. sorted(os.path.split(path) for path in result)]
  101. def clear(self):
  102. """Clear all collected files."""
  103. self.files = set()
  104. self.allfiles = []
  105. def process_directive(self, directive):
  106. """
  107. Process a directive which either adds some files from ``allfiles`` to
  108. ``files``, or removes some files from ``files``.
  109. :param directive: The directive to process. This should be in a format
  110. compatible with distutils ``MANIFEST.in`` files:
  111. http://docs.python.org/distutils/sourcedist.html#commands
  112. """
  113. # Parse the line: split it up, make sure the right number of words
  114. # is there, and return the relevant words. 'action' is always
  115. # defined: it's the first word of the line. Which of the other
  116. # three are defined depends on the action; it'll be either
  117. # patterns, (dir and patterns), or (dirpattern).
  118. action, patterns, thedir, dirpattern = self._parse_directive(directive)
  119. # OK, now we know that the action is valid and we have the
  120. # right number of words on the line for that action -- so we
  121. # can proceed with minimal error-checking.
  122. if action == 'include':
  123. for pattern in patterns:
  124. if not self._include_pattern(pattern, anchor=True):
  125. logger.warning('no files found matching %r', pattern)
  126. elif action == 'exclude':
  127. for pattern in patterns:
  128. found = self._exclude_pattern(pattern, anchor=True)
  129. #if not found:
  130. # logger.warning('no previously-included files '
  131. # 'found matching %r', pattern)
  132. elif action == 'global-include':
  133. for pattern in patterns:
  134. if not self._include_pattern(pattern, anchor=False):
  135. logger.warning('no files found matching %r '
  136. 'anywhere in distribution', pattern)
  137. elif action == 'global-exclude':
  138. for pattern in patterns:
  139. found = self._exclude_pattern(pattern, anchor=False)
  140. #if not found:
  141. # logger.warning('no previously-included files '
  142. # 'matching %r found anywhere in '
  143. # 'distribution', pattern)
  144. elif action == 'recursive-include':
  145. for pattern in patterns:
  146. if not self._include_pattern(pattern, prefix=thedir):
  147. logger.warning('no files found matching %r '
  148. 'under directory %r', pattern, thedir)
  149. elif action == 'recursive-exclude':
  150. for pattern in patterns:
  151. found = self._exclude_pattern(pattern, prefix=thedir)
  152. #if not found:
  153. # logger.warning('no previously-included files '
  154. # 'matching %r found under directory %r',
  155. # pattern, thedir)
  156. elif action == 'graft':
  157. if not self._include_pattern(None, prefix=dirpattern):
  158. logger.warning('no directories found matching %r',
  159. dirpattern)
  160. elif action == 'prune':
  161. if not self._exclude_pattern(None, prefix=dirpattern):
  162. logger.warning('no previously-included directories found '
  163. 'matching %r', dirpattern)
  164. else: # pragma: no cover
  165. # This should never happen, as it should be caught in
  166. # _parse_template_line
  167. raise DistlibException(
  168. 'invalid action %r' % action)
  169. #
  170. # Private API
  171. #
  172. def _parse_directive(self, directive):
  173. """
  174. Validate a directive.
  175. :param directive: The directive to validate.
  176. :return: A tuple of action, patterns, thedir, dir_patterns
  177. """
  178. words = directive.split()
  179. if len(words) == 1 and words[0] not in ('include', 'exclude',
  180. 'global-include',
  181. 'global-exclude',
  182. 'recursive-include',
  183. 'recursive-exclude',
  184. 'graft', 'prune'):
  185. # no action given, let's use the default 'include'
  186. words.insert(0, 'include')
  187. action = words[0]
  188. patterns = thedir = dir_pattern = None
  189. if action in ('include', 'exclude',
  190. 'global-include', 'global-exclude'):
  191. if len(words) < 2:
  192. raise DistlibException(
  193. '%r expects <pattern1> <pattern2> ...' % action)
  194. patterns = [convert_path(word) for word in words[1:]]
  195. elif action in ('recursive-include', 'recursive-exclude'):
  196. if len(words) < 3:
  197. raise DistlibException(
  198. '%r expects <dir> <pattern1> <pattern2> ...' % action)
  199. thedir = convert_path(words[1])
  200. patterns = [convert_path(word) for word in words[2:]]
  201. elif action in ('graft', 'prune'):
  202. if len(words) != 2:
  203. raise DistlibException(
  204. '%r expects a single <dir_pattern>' % action)
  205. dir_pattern = convert_path(words[1])
  206. else:
  207. raise DistlibException('unknown action %r' % action)
  208. return action, patterns, thedir, dir_pattern
  209. def _include_pattern(self, pattern, anchor=True, prefix=None,
  210. is_regex=False):
  211. """Select strings (presumably filenames) from 'self.files' that
  212. match 'pattern', a Unix-style wildcard (glob) pattern.
  213. Patterns are not quite the same as implemented by the 'fnmatch'
  214. module: '*' and '?' match non-special characters, where "special"
  215. is platform-dependent: slash on Unix; colon, slash, and backslash on
  216. DOS/Windows; and colon on Mac OS.
  217. If 'anchor' is true (the default), then the pattern match is more
  218. stringent: "*.py" will match "foo.py" but not "foo/bar.py". If
  219. 'anchor' is false, both of these will match.
  220. If 'prefix' is supplied, then only filenames starting with 'prefix'
  221. (itself a pattern) and ending with 'pattern', with anything in between
  222. them, will match. 'anchor' is ignored in this case.
  223. If 'is_regex' is true, 'anchor' and 'prefix' are ignored, and
  224. 'pattern' is assumed to be either a string containing a regex or a
  225. regex object -- no translation is done, the regex is just compiled
  226. and used as-is.
  227. Selected strings will be added to self.files.
  228. Return True if files are found.
  229. """
  230. # XXX docstring lying about what the special chars are?
  231. found = False
  232. pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
  233. # delayed loading of allfiles list
  234. if self.allfiles is None:
  235. self.findall()
  236. for name in self.allfiles:
  237. if pattern_re.search(name):
  238. self.files.add(name)
  239. found = True
  240. return found
  241. def _exclude_pattern(self, pattern, anchor=True, prefix=None,
  242. is_regex=False):
  243. """Remove strings (presumably filenames) from 'files' that match
  244. 'pattern'.
  245. Other parameters are the same as for 'include_pattern()', above.
  246. The list 'self.files' is modified in place. Return True if files are
  247. found.
  248. This API is public to allow e.g. exclusion of SCM subdirs, e.g. when
  249. packaging source distributions
  250. """
  251. found = False
  252. pattern_re = self._translate_pattern(pattern, anchor, prefix, is_regex)
  253. for f in list(self.files):
  254. if pattern_re.search(f):
  255. self.files.remove(f)
  256. found = True
  257. return found
  258. def _translate_pattern(self, pattern, anchor=True, prefix=None,
  259. is_regex=False):
  260. """Translate a shell-like wildcard pattern to a compiled regular
  261. expression.
  262. Return the compiled regex. If 'is_regex' true,
  263. then 'pattern' is directly compiled to a regex (if it's a string)
  264. or just returned as-is (assumes it's a regex object).
  265. """
  266. if is_regex:
  267. if isinstance(pattern, str):
  268. return re.compile(pattern)
  269. else:
  270. return pattern
  271. if _PYTHON_VERSION > (3, 2):
  272. # ditch start and end characters
  273. start, _, end = self._glob_to_re('_').partition('_')
  274. if pattern:
  275. pattern_re = self._glob_to_re(pattern)
  276. if _PYTHON_VERSION > (3, 2):
  277. assert pattern_re.startswith(start) and pattern_re.endswith(end)
  278. else:
  279. pattern_re = ''
  280. base = re.escape(os.path.join(self.base, ''))
  281. if prefix is not None:
  282. # ditch end of pattern character
  283. if _PYTHON_VERSION <= (3, 2):
  284. empty_pattern = self._glob_to_re('')
  285. prefix_re = self._glob_to_re(prefix)[:-len(empty_pattern)]
  286. else:
  287. prefix_re = self._glob_to_re(prefix)
  288. assert prefix_re.startswith(start) and prefix_re.endswith(end)
  289. prefix_re = prefix_re[len(start): len(prefix_re) - len(end)]
  290. sep = os.sep
  291. if os.sep == '\\':
  292. sep = r'\\'
  293. if _PYTHON_VERSION <= (3, 2):
  294. pattern_re = '^' + base + sep.join((prefix_re,
  295. '.*' + pattern_re))
  296. else:
  297. pattern_re = pattern_re[len(start): len(pattern_re) - len(end)]
  298. pattern_re = r'%s%s%s%s.*%s%s' % (start, base, prefix_re, sep,
  299. pattern_re, end)
  300. else: # no prefix -- respect anchor flag
  301. if anchor:
  302. if _PYTHON_VERSION <= (3, 2):
  303. pattern_re = '^' + base + pattern_re
  304. else:
  305. pattern_re = r'%s%s%s' % (start, base, pattern_re[len(start):])
  306. return re.compile(pattern_re)
  307. def _glob_to_re(self, pattern):
  308. """Translate a shell-like glob pattern to a regular expression.
  309. Return a string containing the regex. Differs from
  310. 'fnmatch.translate()' in that '*' does not match "special characters"
  311. (which are platform-specific).
  312. """
  313. pattern_re = fnmatch.translate(pattern)
  314. # '?' and '*' in the glob pattern become '.' and '.*' in the RE, which
  315. # IMHO is wrong -- '?' and '*' aren't supposed to match slash in Unix,
  316. # and by extension they shouldn't match such "special characters" under
  317. # any OS. So change all non-escaped dots in the RE to match any
  318. # character except the special characters (currently: just os.sep).
  319. sep = os.sep
  320. if os.sep == '\\':
  321. # we're using a regex to manipulate a regex, so we need
  322. # to escape the backslash twice
  323. sep = r'\\\\'
  324. escaped = r'\1[^%s]' % sep
  325. pattern_re = re.sub(r'((?<!\\)(\\\\)*)\.', escaped, pattern_re)
  326. return pattern_re